import os
import re
import subprocess
import sys
from time import sleep


BASE_PATH = "/Users/zhangbeibei/Downloads/"

# 严格按你定义的顺序（匹配版本号前的内容）
INSTALL_ORDER = [
    r"Release_com\.winmate\.native_",  # 第1顺位
    r"Release_com\.winmate\.ntshare_",  # 第2顺位
    r"Release_com\.winmate\.native\.fb_",  # 第3顺位
    r"Release_com\.winmate\.ntshare\.fb_",  # 第4顺位
    r"Release_com\.winmate\.native\.gg_",  # 第5顺位
    r"Release_com\.winmate\.ntshare\.gg_",  # 第6顺位
    r"Release_com\.winmate\.appshare_"  # 第7顺位
]


def should_skip(apk_name):
    """检查是否是需要跳过的PreInstall包"""
    return apk_name.startswith("PreInstall_com.winmate.native_")


def extract_package_name(apk_path):
    """从APK路径提取包名（如 com.winmate.native.gg）"""
    apk_name = os.path.basename(apk_path)
    match = re.search(r"_(com\..+?)_\d", apk_name)  # 匹配com.开头到版本号前的部分
    return match.group(1) if match else None


def uninstall_package(pkg_name):
    """静默卸载包（如果存在）"""
    print(f"🔄 尝试卸载: {pkg_name}", end=" → ")
    result = subprocess.run(
        ["adb", "shell", "pm", "uninstall", "--user", "0", pkg_name],
        capture_output=True,
        text=True
    )
    if "Success" in result.stdout:
        print("✅ 卸载成功")
        return True
    elif "not installed" in result.stdout:
        print("⚠️ 未安装")
        return False
    else:
        print(f"❌ 失败: {result.stdout.strip()}")
        return False


def get_full_path(relative_path):
    relative_path = relative_path.strip('"\"')
    return os.path.join(BASE_PATH, relative_path)


def install_apk(apk_path):
    """安装APK并返回是否成功"""
    print(f"📦 正在安装: {os.path.basename(apk_path)}", end=" → ")
    result = subprocess.run(
        ["adb", "install", "-r", apk_path],
        capture_output=True,
        text=True
    )
    if "Success" in result.stdout:
        print("✅ 安装成功")
        return True
    else:
        print(f"❌ 失败: {result.stderr or result.stdout.strip()}")
        return False


def process_apk(apk_path):
    """处理单个APK：卸载旧版 → 安装新版"""
    pkg_name = extract_package_name(apk_path)
    if not pkg_name:
        print(f"⚠️ 无法提取包名: {apk_path}")
        return False

    uninstall_package(pkg_name)
    sleep(1)  # 给设备缓冲时间
    return install_apk(apk_path)


def main():
    # 检查设备连接
    if not subprocess.run(["adb", "devices"], capture_output=True).stdout.decode().count("\tdevice"):
        print("错误：未检测到已连接的Android设备！")
        sys.exit(1)

    # 获取APK文件夹
    relative_path = input("请输入版本子路径（如1.6.0/1.6.0/）:")
    folder = get_full_path(relative_path)

    apks = [
        os.path.join(folder, f)
        for f in os.listdir(folder)
        if f.endswith('.apk') and not should_skip(f)
    ]

    # 按优先级排序
    def get_priority(apk_path):
        apk_name = os.path.basename(apk_path)
        for i, pattern in enumerate(INSTALL_ORDER):
            if re.search(pattern, apk_name):
                return i
        return len(INSTALL_ORDER)

    sorted_apks = sorted(apks, key=get_priority)

    print(f"\n🔍 扫描路径：{folder}")
    print(f"📦 找到 {len(apks)} 个待安装APK（已跳过PreInstall）")

    print("\n⚙️ 处理顺序：")
    for i, apk in enumerate(sorted_apks, 1):
        print(f" {i:>2d}. {os.path.basename(apk)}")

    # 确认操作
    if input("\n确认执行卸载+安装？(y/n): ").lower() != 'y':
        sys.exit(0)

    # 批量处理
    success = 0
    for apk in sorted_apks:
        if process_apk(apk):
            success += 1
        sleep(2)  # 防止设备过载
        print(f"🎯 成功 {success}/{len(sorted_apks)} 个\n")

    print(f"\n🎯 操作完成！成功 {success}/{len(sorted_apks)} 个")


if __name__ == "__main__":
    main()